package co.za.itweb.itwebpro;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;

public class Search extends Activity{
	Uri url;
	String URLL;
	protected static final String PREFS_NAME = "QUERYFIELDS";
	private MainAsyncTask MAT;
	InputStream is;
	String result;
	Search myactivity;
   
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_overlay);
		 
		MAT = new MainAsyncTask(this);
		MAT.execute();
	}

	public class MainAsyncTask extends AsyncTask<Void, Integer, Void> {
		
		public MainAsyncTask(Activity activity) {
			myactivity = (Search) activity;
		}

		protected void onPreExecute() {

		}

		@Override
		protected Void doInBackground(Void... arg0) {

			try {

				if(parseConfig()){
					System.out.println("PARSED");
					
				}else{
					Intent returnIntent = new Intent();	
					setResult(0, returnIntent);
					SearchActivity.List.clear();
					SearchActivity.sections.clear();
					SearchActivity.jsonObject=null;
					finish();
				}

			} catch (FileNotFoundException e) {

				e.printStackTrace();
			} catch (IOException e) {

				e.printStackTrace();
			}

			if (isCancelled()) {
				Intent returnIntent = new Intent();
				setResult(0, returnIntent);
				finish();
			}

			return null;
		}

		@Override
		protected void onProgressUpdate(Integer... values) {

		}

		
		@Override
		protected void onPostExecute(Void result) {
			Intent returnIntent = new Intent();
			returnIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			setResult(1, returnIntent);
			
			finish();
		}

		
	}
	
	public boolean parseConfig() throws FileNotFoundException, IOException {
		URLL="http://itweb.mobi/__itweb_pro/feed/iosv3/_load.php?searchString="+SearchActivity.searchterm+"&searchDatabase="+SearchActivity.database+"&searchType=phrase";
		URLL=URLL.replaceAll(" ", "%20");
	
		
		try {

			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(URLL);

			JSONObject obj = new JSONObject();
			obj.put("conf", "conf");
			httppost.setEntity(new StringEntity(obj.toString(), "UTF-8"));

			httppost.setHeader("Accept", "application/json");
			httppost.setHeader("Content-type", "application/json");

			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();

		} catch (Exception e) {
			Log.e("log_tag", "Error in http connection " + e.toString());
			return false;
		}

		try {
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(is, "iso-8859-1"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");

			}

			is.close();
			result = sb.toString();

		} catch (Exception e) {
			Log.e("log_tag", "Error converting result " + e.toString());
			return false;
		}

		// try parse the string to a JSON object
		try {
			SearchActivity.jsonObject = new JSONObject(result);
		    System.out.println(SearchActivity.jsonObject);
		    
		    SearchActivity.sectionsOrder = SearchActivity.jsonObject
					.getJSONArray("sections_order");
		    SearchActivity.sectionsName = SearchActivity.jsonObject
					.getJSONObject("sections_available");

		    SearchActivity.sectionsOrdering = JsonUtil2
					.getStringListFromJsonArray(SearchActivity.sectionsOrder);
			
			return true;

		} catch (JSONException e) {
			Log.e("log_tag", "Error parsing data " + e.toString());

		}

		return false;

	}

	

}
